<template>
  <div>
    <h2>{{ course.title }} 的章节列表</h2>
    <a-table :data-source="chapters" :columns="chapterColumns" row-key="chapterId">
      <template #action="{ record }">
        <a-space>
          <a-button @click="editChapter(record)" type="primary" size="small">编辑</a-button>
          <a-button danger @click="deleteChapter(record.chapterId)" size="small">删除</a-button>
        </a-space>
      </template>
    </a-table>
    <a-button type="primary" @click="showAddChapterModal">添加章节</a-button>

    <!-- 添加章节的模态框 -->
    <a-modal v-model:visible="isAddChapterModalVisible" title="添加章节" @ok="handleAddChapter" @cancel="closeAddChapterModal">
      <a-form :model="newChapter" labelAlign="right" layout="vertical">
        <a-form-item label="章节名称:">
          <a-input v-model:value="newChapter.title" placeholder="请输入章节名称" />
        </a-form-item>
        <a-form-item label="章节描述:">
          <a-textarea v-model:value="newChapter.description" placeholder="请输入章节描述" />
        </a-form-item>
        <a-form-item label="排序:">
          <a-input-number v-model:value="newChapter.sortOrder" placeholder="请输入排序" />
        </a-form-item>
        <a-form-item label="视频文件:">
          <a-upload
              v-model:file-list="fileList"
              name="file"
              action="http://localhost:5173/api/online/videos/upload"
              :headers="headers"
              @change="handleChange"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              Click to Upload
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑章节的模态框 -->
    <a-modal v-model:visible="isEditModalVisible" title="编辑章节" @ok="handleEditChapter" @cancel="closeEditModal">
      <a-form :model="editChapterData" labelAlign="right" layout="vertical">
        <a-form-item label="章节名称:">
          <a-input v-model:value="editChapterData.title" placeholder="请输入章节名称" />
        </a-form-item>
        <a-form-item label="章节描述:">
          <a-textarea v-model:value="editChapterData.description" placeholder="请输入章节描述" />
        </a-form-item>
        <a-form-item label="视频链接:">
          <a-input v-model:value="editChapterData.playUrl" placeholder="请输入视频链接" />
        </a-form-item>
        <a-form-item label="排序:">
          <a-input-number v-model:value="editChapterData.sortOrder" placeholder="请输入排序" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 确认删除的模态框 -->
    <a-modal v-model:visible="isDeleteModalVisible" title="确认删除" @ok="handleDeleteChapter" @cancel="closeDeleteModal">
      <p>你确定要删除这个章节吗？{{ confirmDeleteChapterId }}</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted,h } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {addChapter, deletesChapter, getChapters} from "@/apis/chapter.js";
import {useUserStore} from "@/stores/user.js";  // Ensure axios is imported
import {useRoute} from "vue-router";

// 路由参数
const route = useRoute();
const courseId = route.params.courseId;



// 状态管理
const chapters = ref([]);
const course = ref({});
const isAddChapterModalVisible = ref(false);
const isEditModalVisible = ref(false);
const isDeleteModalVisible = ref(false);
const newChapter = ref({ title: '', description: '', playUrl: '' ,courseId: courseId,sortOrder: 0});
const editChapterData = ref({});
const confirmDeleteChapterId = ref(null);
const videoFile = ref(null); // Track the uploaded file

// 获取数据
const fetchMockData =async () => {
  const res=await getChapters(courseId)
  console.log(res)
  course.value = res.data.courses; // 获取课程信息
  chapters.value = res.data.chapterVoList; // 获取章节列表
};

// 组件挂载时获取章节数据
onMounted(() => {
  fetchMockData();
});

// 显示添加章节的模态框
const showAddChapterModal = () => {
  newChapter.value = { title: '', description: '', playUrl: '',courseId: courseId };
  videoFile.value = null; // Reset the file input
  isAddChapterModalVisible.value = true;
};

// 处理文件上传
const handleChange =  (info) => {
  console.log('Upload event:', info)
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    newChapter.value.playUrl=info.file.response.data.playUrl
    message.success(`${info.file.name} 文件上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败。`);
  }
};
const fileList = ref([]);
const userStore =useUserStore()
const headers = {
  authorization: userStore.getToken(),
};

// 添加章节
const handleAddChapter = async () => {
  try {
    const res=await addChapter(newChapter.value);
    if (res.code===1){
      message.success(res.message)
      fetchMockData(); // 刷新章节列表
      isAddChapterModalVisible.value = false; // 关闭模态框
    }
  } catch (error) {
    message.error('添加章节失败，请重试。');
  }
};

// 关闭添加章节模态框
const closeAddChapterModal = () => {
  isAddChapterModalVisible.value = false;
};

// 编辑章节
const editChapter = (chapter) => {
  editChapterData.value = { ...chapter };
  isEditModalVisible.value = true;
};

// 处理编辑章节
const handleEditChapter = () => {
  const index = chapters.value.findIndex(chapter => chapter.chapterId === editChapterData.value.chapterId);
  if (index !== -1) {
    chapters.value[index] = editChapterData.value;
  }
  isEditModalVisible.value = false;
};

// 关闭编辑章节模态框
const closeEditModal = () => {
  isEditModalVisible.value = false;
};

// 删除章节
const deleteChapter = (chapterId) => {
  confirmDeleteChapterId.value = chapterId;
  isDeleteModalVisible.value = true;
};

// 处理删除章节
const handleDeleteChapter =async () => {

  const res =await deletesChapter(confirmDeleteChapterId.value)
  if (res.code===1){
    message.success("删除成功")
    fetchMockData();
  }
  confirmDeleteChapterId.value = null;
  isDeleteModalVisible.value = false;
};

// 关闭删除章节模态框
const closeDeleteModal = () => {
  confirmDeleteChapterId.value = null;
  isDeleteModalVisible.value = false;
};

// 定义章节表格列
const chapterColumns = [
  {
    title: '章节名称',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
  },
  {
    title: '视频链接',
    dataIndex: 'playUrl',
    key: 'playUrl',
    customRender: (a) => {
      return h('video', {
        src: a.value,
        controls: true,
        width: '200', // 可以根据需求调整宽度
      });
    },
  },
  {
    title: '排序',
    dataIndex: 'sortOrder',
    key: 'sortOrder',
    sorter: (a, b) => a.sortOrder - b.sortOrder,
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    slots: { customRender: 'action' },
  },
];
</script>

<style scoped>
/* 可以在这里添加样式 */
</style>
